package com.smartwebee.android.blespp.hospital.selftest;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.smartwebee.android.blespp.R;
import com.smartwebee.android.blespp.bean.AllQuestions;
import com.smartwebee.android.blespp.bean.SelfTestBean;
import com.smartwebee.android.blespp.bean.SelfTestSingleQuestion;
import com.smartwebee.android.blespp.databinding.ActivitySelfTestV2Binding;
import com.smartwebee.android.blespp.hospital.BaseActivity;
import com.smartwebee.android.blespp.hospital.adapter.SelfTestAdapter;
import com.smartwebee.android.blespp.hospital.fragment.SelfTestFragment;
import com.smartwebee.android.blespp.http.HttpRequest;
import com.smartwebee.android.blespp.http.RequestInterface;
import com.smartwebee.android.blespp.http.VolleyReqQueue;
import com.smartwebee.android.blespp.resp.BaseResp;
import com.smartwebee.android.blespp.utils.UIUtils;
import com.smartwebee.android.blespp.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class SelfTestActivity extends BaseActivity implements AdapterView.OnItemClickListener, RequestInterface {
    private ActivitySelfTestV2Binding binding;
    private SelfTestAdapter adapter;
    private AllQuestions allQuestions;
    private int questionPosition = 0;
    private SelfTestSingleQuestion question;
    private String uploadType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_self_test_v2);
        TAG = "SelfTestActivity";
        fetchQuestions();
        initView();
        requestQueue = VolleyReqQueue.getInstance(this).getRequestQueue();
    }

    private void fetchQuestions() {
        String type = getIntent().getStringExtra(SelfTestFragment.INTENT_TITLE);
        if (type.equals(SelfTestFragment.TYPE1)) {
            uploadType = "1";
            allQuestions = new Gson().fromJson(Utils.firstQuestionJson, AllQuestions.class);
        } else if (type.equals(SelfTestFragment.TYPE2)) {
            uploadType = "2";
            allQuestions = new Gson().fromJson(Utils.secondQuestionJson, AllQuestions.class);
        } else if (type.equals(SelfTestFragment.TYPE3)) {
            uploadType = "3";
            allQuestions = new Gson().fromJson(Utils.thirdQuestionJson, AllQuestions.class);
        } else if (type.equals(SelfTestFragment.TYPE4)) {
            uploadType = "4";
            allQuestions = new Gson().fromJson(Utils.fourthQuestionJson, AllQuestions.class);
        }

    }

    private void initView() {
        binding.btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                httpUploadScore();
            }
        });
        binding.tvHead.setText(getIntent().getStringExtra(SelfTestFragment.INTENT_TITLE));
        adapter = new SelfTestAdapter(this, new ArrayList<SelfTestBean>());
        binding.listviewQuestion.setAdapter(adapter);
        binding.listviewQuestion.setOnItemClickListener(this);
        binding.tvPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                questionPosition--;
                setQuestion();
            }
        });

        setQuestion();
    }

    private void setQuestion() {
        question = allQuestions.getAllQuestions().get(questionPosition);
        checkPositionStatus();
        binding.tvTitle.setText(question.getTitle());
        adapter.setItems(question.getQuestions());
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        drawItem(position);
        adapter.notifyDataSetChanged();
        if (questionPosition == allQuestions.getAllQuestions().size() - 1) {
            binding.btnSubmit.setVisibility(View.VISIBLE);
            binding.tvScore.setVisibility(View.VISIBLE);
            binding.tvScore.setText("总分: " + getSum());
        }
        if (questionPosition < allQuestions.getAllQuestions().size() - 1) {
            Observable.just("")
                    .delay(100, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String s) {
                            questionPosition++;
                            setQuestion();
                        }
                    });
        }
    }

    private void drawItem(int position) {
        for (int i = 0; i < question.getQuestions().size(); i ++) {
            if (i == position) {
                question.getQuestions().get(i).setSelected(true);
            } else {
                question.getQuestions().get(i).setSelected(false);
            }
        }
    }

    private void checkPositionStatus() {
        if (checkFirstQuestion()) {
            binding.tvPrevious.setVisibility(View.GONE);
        } else {
            binding.tvPrevious.setVisibility(View.VISIBLE);
        }
        if (checkLastQuestion()) {
            binding.tvNext.setVisibility(View.GONE);
            binding.tvScore.setVisibility(View.GONE);
        } else {
            binding.btnSubmit.setVisibility(View.GONE);
            binding.tvScore.setVisibility(View.GONE);
            binding.tvNext.setVisibility(View.GONE);
        }
    }

    private String getSum() {
        int sum = 0;
        for (int i = 0; i < allQuestions.getAllQuestions().size(); i++) {
            for (int j = 0; j < allQuestions.getAllQuestions().get(i).getQuestions().size(); j++) {
                if (allQuestions.getAllQuestions().get(i).getQuestions().get(j).isSelected()) {
                    sum += Integer.valueOf(allQuestions.getAllQuestions().get(i).getQuestions().get(j).getScore());
                }
            }
        }
        return sum + "";
    }

    private String getDetail() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < allQuestions.getAllQuestions().size(); i++) {
            for (int j = 0; j < allQuestions.getAllQuestions().get(i).getQuestions().size(); j++) {
                if (allQuestions.getAllQuestions().get(i).getQuestions().get(j).isSelected()) {
                    sb.append(allQuestions.getAllQuestions().get(i).getQuestions().get(j).getQuestion());
                    sb.append("  ");
                    sb.append(allQuestions.getAllQuestions().get(i).getQuestions().get(j).getScore());
                    sb.append("分");
                    sb.append(",");
                }
            }
        }
        return sb.toString();
    }

    private boolean checkFirstQuestion() {
        return questionPosition == 0;
    }

    private boolean checkLastQuestion() {
        return questionPosition == allQuestions.getAllQuestions().size() - 1;
    }

    private void httpUploadScore() {
        showLoading();
        HttpRequest httpRequest = new HttpRequest(Request.Method.POST, Utils.uploadScore,
                this) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("sn", Utils.registerResp.getData().getSn());
                map.put("sid", uploadType);
                map.put("score", getSum() + "");
                map.put("detail", getDetail());
                return map;
            }
        };
        requestQueue.add(httpRequest);
    }

    @Override
    public void onSuccess(String id, String resp) {
        dismissLoading();
        BaseResp baseResp = new Gson().fromJson(resp, BaseResp.class);
        if (Utils.parseData(baseResp)) {
            UIUtils.showToast(this, "得分上传成功");
            finish();
        } else {
            UIUtils.showTips(this, baseResp.getMsg());
        }
    }

    @Override
    public void onError(String error) {
        dismissLoading();
        UIUtils.showTips(this, error);
    }
}
